<?php
namespace Hphp\Foundation\Http;

use Hphp\Contracts\Http\Kernel as Contracts;
use Hphp\Foundation\Application;
use Hphp\Pipeline\Pipeline;
use Hphp\Request\Request;

// 处理http请求的核心对象
class Kernel implements Contracts
{
    /**
     * [protected description]
     * @var \Hphp\Foundation\Application
     */
    protected $app;

    protected $middleware;

    /**
     * 保存驱动类
     * @var [type]
     */
    protected $bootstrappers = [
        \Hphp\Foundation\Bootstrap\RegisterFacades::class,
        \Hphp\Foundation\Bootstrap\LoadConfiguration::class,
        \Hphp\Foundation\Bootstrap\RegisterProviders::class,
        \Hphp\Foundation\Bootstrap\BootProviders::class,
    ];

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function handle(Request $request)
    {
        return $this->sendRequestThroughRouter($request);
    }

    /**
     * 根据请求分发到相应的路由并且输出运行结果
     */
    public function sendRequestThroughRouter(Request $request)
    {
        $this->app->make('events')->dispatcher('systemct.log',['项目根据请求转发']);

        // 加载框架的驱动方法
        $this->bootstrap();

        $this->app->instance('request', $request);
        // 进行请求转发
        // return $this->app->make('route')->dispatch($request);
        return (new Pipeline($this->app))
            ->send($request)
            ->through($this->middleware)
            ->then($this->dispatchToRouter());
    }

    protected function dispatchToRouter()
    {
        return function ($request) {
            $this->app->instance('request', $request);

            return $this->app->make('route')->dispatch($request);
        };
    }

    /**
     * 加载框架的驱动方法
     * @return [type] [description]
     */
    public function bootstrap()
    {
        // $this->app->bootstrapWith($this->bootstrappers);

        foreach ($this->bootstrappers as $bootstrapper) {
            $this->app->make($bootstrapper)->bootstrap($this->app);
        }
    }
}